package models

import (
	"github.com/jinzhu/gorm"
	"reflect"
	"yanwc.gokit/user_svc/common"
)
import _ "github.com/go-sql-driver/mysql"

var (
	Db *gorm.DB
	e  error
)

//初始化数据
func init() {
	initDB()
	initDefaultAccount()
}

func initDB() {
	Db, e = gorm.Open("mysql", "dev_user:0078abCD@(dev-user.mysql.zhangbei.rds.aliyuncs.com)/dev?charset=utf8&parseTime=True&loc=Local")
	//defer Db.Close()
	if e != nil {
		panic(e)
	}
	Db.LogMode(true)
	//初始化表结构
	Db.AutoMigrate(
		&User{},
		&Account{},
		&Role{},
		&Code{},
		&LoginLog{},
	)
	Db.Model(&Account{}).AddUniqueIndex("udx_subSystemId_loginName_loginType", "sub_system_id", "login_name", "login_type")
	Db.Model(&Role{}).AddUniqueIndex("udx_name_subSystemId", "name", "sub_system_id")
	Db.Model(&LoginLog{}).AddIndex("idx_login_at", "login_at")
	Db.Model(&User{}).AddIndex("idx_createdAt", "created_at")
}

func initDefaultAccount() bool {
	var account Account
	var user User
	errs := Db.Where("login_name=? and login_type=? and sub_system_id = ? ", "admin", UserNameAndPassword, 0).Preload("User").First(&account).GetErrors()
	if len(errs) > 0 {
		panic("查找系统默认用户失败")
	}
	if reflect.DeepEqual(account, Account{}) {
		newUser := User{Name: "默认管理员", NickName: "默认管理员"}
		Db.Create(&user)
		a := new(Account)
		a.User = newUser
		a.LoginType = UserNameAndPassword
		a.LoginName = "admin"
		a.Password = common.Md5("123456")
		a.SubSystemId = 0
		a.UserId = user.ID
		Db.Create(a)
	}
	return true
}
